
// Get the "extensions.gtplugin." branch

var prefs = GTPlugin_getPrefs();
var GTPlugin_activated = 0;
var GTPlugin_result = 2;
var GTPlugin_selectedTyp = -1;
var GTPlugin_selectedWer = -1;
var GTPlugin_selectedGalaxy = -1;
var GTPlugin_selectedSystem = -1;
var GTPlugin_selectedRanks = -1;
var GTPlugin_Doc;
var GTPlugin_alarmenabled = 0;
var GTPlugin_grefreshenabled = 0;
var GTPlugin_ogameversion = "0.74";

function init() { GTPlugin_ext.init(); }

window.addEventListener("load", init, false);

var GTPlugin_ext = {
    init: function() {
        var appcontent = document.getElementById("appcontent");   // browser
        if(appcontent)
        appcontent.addEventListener("load", this.onPageLoad, true);
        var messagepane = document.getElementById("messagepane"); // mail
        if(messagepane)
        messagepane.addEventListener("load", this.onPageLoad, true);
        var prefs = GTPlugin_getPrefs();
        if (prefs.getBoolPref("gtplugin.settings.autostarten") == true)
        GTPlugin_Activate();
    },

    onPageLoad: function(aEvent) {

        if (GTPlugin_activated == 0) return;
        var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
        var text;
        // do something with the loaded page.
        // doc.location is a Location object (see below for a link).
        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString( "toolbar.status.nothing" );
        GTPlugin_Doc = null;
        document.getElementById("GTPlugin-uploads").disabled = true;
        //alert("doc.location.href is : " + doc.location.href);
        
        /* ALARM */
        if(GTPlugin_alarmenabled == 1 && GTPlugin_IsOverview(doc)) {
        	var url1 = null;
        	if(prefs.prefHasUserValue("gtplugin.settings.alarmsoundurl"))
        		url1 = prefs.getCharPref("gtplugin.settings.alarmsoundurl");
        	if(!url1 || url1.length < 7) url1 = "http:\/\/www.utblog.com\/galaxytool\/alarm.mid";
        	document.getElementById("GTPlugin-alarm-view").value = GTPlugin_GetLocString("toolbar.alarminfo.working");
		var i = 0;
		var beattacked = false;
		var spans = doc.getElementsByTagName('span');
		var enablespy = true;
		if(prefs.prefHasUserValue("gtplugin.settings.enablespy"))
			enablespy = prefs.getBoolPref("gtplugin.settings.enablespy");
		for(i=0; i<spans.length; i++) {
			if(spans[i].className == 'flight attack' || (enablespy && spans[i].className=='flight espionage')) {
				var soundobj = doc.createElement("div");
				soundobj.innerHTML = '<embed src="' + url1 + '" id="UTAlarmSound" hidden="true" border="0" width="0" height="0" autostart="true" loop="true" enablejavascript="true"\/>';
				doc.body.appendChild(soundobj);
				beattacked = true;
				break;
			}
		}
		if(!beattacked) {
	        	var timeout = (Math.random()*5+3)*60*1000;
			var anchors2 = doc.getElementsByTagName('a');
			var beFattacked = false;
			for(i=0;i<anchors2.length;i++) {
				if(anchors2[i].href.search(/index\.php\?page=renameplanet/i) > -1 || anchors2[i].href.search(/renameplanet\.php/i) > -1)
				{
					var td = anchors2[i].parentNode;
					td.innerHTML = td.innerHTML + '&nbsp;&nbsp;<span style="color:red;">Reload after<\/span>&nbsp' + '<span id="bxxalarm" title="'+ Math.floor(timeout/1000.0) + '"><\/span>';
					beFattacked = true;
					break;
				}
			}
			if(!beFattacked) {
				var disp = doc.createElement("div");
				disp.setAttribute("style", "text-align:center;");
				disp.innerHTML = '&nbsp;&nbsp;<span style="color:red;">Reload after<\/span>&nbsp' + '<span id="bxxalarm" title="'+ Math.floor(timeout/1000.0) + '"><\/span>';
				doc.body.appendChild(disp);
			}
	        	
	        	var tosctarray = new Array();
	        	i = 0;
	        	tosctarray[i++] = 'function UTGTPAttackDetector() {';
	        	tosctarray[i++] = 'document.location.reload();';
	        	tosctarray[i++] = '}';
	        	
			ss = '	function ta(){ \
				    bxx = document.getElementById(\'bxxalarm\');	\
				    ss = bxx.title;	\
				    s = ss;	\
				    m = 0;	\
				    h = 0;	\
				    if (s < 0) {	\
				      bxx.innerHTML = "-";	\
				    } else {	\
				      if (s > 59) {	\
					m = Math.floor(s\/60);	\
					s = s - m * 60;	\
				      }	\
				      if (m > 59) {	\
					h = Math.floor(m \/ 60);	\
					m = m - h * 60;	\
				      }	\
				      if (s < 10) {	\
					s = "0" + s;	\
				      }	\
				      if (m < 10) {	\
					m = "0" + m;	\
				      }	\
				      bxx.innerHTML = h + ":" + m + ":" + s + "";	\
				    }	\
				    bxx.title = bxx.title - 1;	\
				  window.setTimeout("ta();", 999);	\
				}';
			var sctarray = new Array();
	        	i = 0;
	        	sctarray[i++] = 'setTimeout("UTGTPAttackDetector();", ' + Math.round(timeout) + ');';
	        	sctarray[i++] = 'ta();';
	        	
	        	var sct = tosctarray.join("") + "\n" + ss + "\n" + sctarray.join("");
	        	var scobj = doc.createElement("script");
	        	scobj.innerHTML = sct;
	        	doc.body.appendChild(scobj);
	        }
        } else if(GTPlugin_alarmenabled == 1 && doc.location.href.search(/\/game\//i) > -1 && doc.location.href.search(/\/game\/leftmenu\.php/i) == -1) {
        	document.getElementById("GTPlugin-alarm-view").value = GTPlugin_GetLocString("toolbar.alarminfo.standby");
        }
        /* -ALARM- */
               
        if(GTPlugin_IsGalaxy(doc)) { 
        	var fm = doc.getElementById('galaxy_form');               	
            //GTPlugin_selectedGalaxy = GTPlugin_getGalaxy(doc);
            //GTPlugin_selectedSystem = GTPlugin_getSystem(doc);
            GTPlugin_selectedGalaxy = Number(fm.elements.namedItem('galaxy').value);
            GTPlugin_selectedSystem = Number(fm.elements.namedItem('system').value);
            document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("galaxyfound.prefix")+GTPlugin_selectedGalaxy+":"+GTPlugin_selectedSystem+GTPlugin_GetLocString("galaxyfound.suffix");
    	    if(prefs.prefHasUserValue("gtplugin.settings.autouploads") && prefs.getBoolPref("gtplugin.settings.autouploads") == true) {
	            text = GTPlugin_get_galaxyview_data(doc);
	            GTPlugin_result = GTPlugin_sendText("galaxy",text,doc.location.href);
	    } else
	    	GTPlugin_Doc = doc;
	    if(GTPlugin_grefreshenabled == 1) {
    	        	var disp = doc.createElement("div");
	        	disp.setAttribute("style", "text-align:center;color:lime;font-weight:bold;");
	        	disp.innerHTML = "Auto Galaxy Right Navigation Enabled...";
	        	doc.body.appendChild(disp);
			var galaxy = GTPlugin_selectedGalaxy;
			var system0 = GTPlugin_selectedSystem;
			if(galaxy==9 && system0==499) {
				disp.innerHTML = disp.innerHTML + "[finished]";
			}
			else {
				if(system0<499) system0+=1;
				else {
					system0=1;
					galaxy+=1;
				}
				var timeout = (Math.random()/3+3)*1000;
				var tosct = "function UTGTPGAutoGalaxyRight() {var fm=document.getElementById('galaxy_form');fm.galaxy.value=" + galaxy + ";fm.system.value=" + system0 + ";fm.submit();;}\nsetTimeout(\"UTGTPGAutoGalaxyRight();\"," + Math.round(timeout) + ");";
				disp.innerHTML = disp.innerHTML + " -> [" + galaxy + ":" + system0 + "]";
				var scobj = doc.createElement("script");
				scobj.innerHTML = tosct;
				doc.body.appendChild(scobj);
			}
	    }
        }
        
        if(GTPlugin_IsStat(doc)) {
            GTPlugin_selectedTyp = GTPlugin_getStatsTyp(doc);
            GTPlugin_selectedWer = GTPlugin_getStatsWho(doc);
            GTPlugin_selectedRanks = GTPlugin_getStatswhitch(doc);
            document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("statsfound");

            //var text = GTPlugin_getStatsText(doc);
            //GTPlugin_result = GTPlugin_sendText("stats",text,doc.location.href);
            GTPlugin_Doc = doc;
        }
        /*        
        if(doc.location.href.search(/\/game\/messages\.php/i) > -1) {
            document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("reportsfound");
            GTPlugin_Doc = doc;
        }

        // Allyhistory
        if((doc.location.href.search(/\/game\/allianzen\.php/i) > -1) && (doc.location.href.search("&a=4") > -1)) {
            GTPlugin_result = GTPlugin_sendText("allyhistory",doc.getElementsByTagName("table")[4].innerHTML,doc.location.href);
        }
	*/
	document.getElementById("GTPlugin-uploads").disabled = (GTPlugin_Doc == null);
    }
}

function GTPlugin_IsOverview(docroot) {
	return (docroot.location.href.search(/\/game\/index\.php\?page=overview/i) > -1) || (docroot.location.href.search(/\/game\/overview\.php/i) > -1);
}

function GTPlugin_IsGalaxy(docroot) {
	return (docroot.location.href.search(/\/game\/index\.php\?page=galaxy/i) > -1) || (docroot.location.href.search(/\/game\/galaxy\.php/i) > -1);
}

function GTPlugin_IsStat(docroot) {
	return (docroot.location.href.search(/\/game\/index\.php\?page=stat/i) > -1) || (docroot.location.href.search(/\/game\/stat\.php/i) > -1);
}

function GTPlugin_FindReports() {
    // get information about what ranks were selected
    try {
    	if(GTPlugin_Doc.location.href.search(/\/game\/messages\.php/i) > -1) {
	        var messageElements = GTPlugin_Doc.getElementsByTagName("table")[5].innerHTML;
	        GTPlugin_result = GTPlugin_sendText("reports",messageElements,GTPlugin_Doc.location.href);
	}
    } catch(e) {
        //alert(e);
    }
}

function GTPlugin_getGalaxy(docroot) {
    // get information about what galaxy selected
    try {
        if (parseInt(docroot.getElementsByTagName("input")[3].value) > 0) {
            return docroot.getElementsByTagName("input")[3].value;
        } else {
            return docroot.getElementsByTagName("input")[4].value;
        }
    } catch (e){
        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("gt_error.gvnotupdated");
        //alert(GTPlugin_GetLocString("erroralert: ")+e);
        return -1;
    }
}

function GTPlugin_getSystem(docroot) {
    // get information about what system selected
    try {
        if (parseInt(docroot.getElementsByTagName("input")[6].value) > 0) {
            return docroot.getElementsByTagName("input")[6].value;
        } else {
            return docroot.getElementsByTagName("input")[7].value;
        }
    } catch (e){
        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("gt_error.gvnotupdated");
        //alert(GTPlugin_GetLocString("erroralert: ")+e);
        return -1;
    }

}

function GTPlugin_getStatsWho(docroot) {
    // get information about what was selected - player=0 or ally=1
    var optionElements = docroot.getElementsByTagName("select")[1].getElementsByTagName("option");
    for (var j = 0; j < optionElements.length; j++) {
        var optionElement = optionElements.item(j);
        if (optionElement.hasAttribute("selected")) {
            return j;
        }
    }
    return -1;
}


function GTPlugin_getStatsTyp(docroot) {
    // get information about what was selected - points=0 or fleet=1 or research=2
    var optionElements = docroot.getElementsByTagName("select")[2].getElementsByTagName("option");
    for (var j = 0; j < optionElements.length; j++) {
        var optionElement = optionElements.item(j);
        if (optionElement.hasAttribute("selected")) {
            return j;
        }
    }
    return -1;
}

function GTPlugin_getStatswhitch(docroot) {
    // get information about what ranks were selected
    var optionElements = docroot.getElementsByTagName("select")[3].getElementsByTagName("option");
    for (var j = 0; j < optionElements.length; j++) {
        var optionElement = optionElements.item(j);
        if (optionElement.hasAttribute("selected")) {
            return optionElement.innerHTML;
            //return j;
        }
    }
    return -1;
}

function GTPlugin_getStatsText(docroot) {
    /* Most parts used from Dr|Willy's Version */
    var tables = docroot.getElementsByTagName('table');
    var tabind;
    for(tabind=0; tabind<tables.length; tabind++)
    	if(tables[tabind].rows.length>=100) break;
    var rows = tables[tabind].rows;
    var cells;
    if(GTPlugin_selectedWer == 0) { //Players
        var ranks = new Array(100);
        var players = new Array(100);
        var pIds = new Array(100);
        var alliances = new Array(100);
        var points = new Array(100);
        var j;
        var pIdRegExp = /messageziel\=(\d+)/;

        for(var i = rows.length - 2; i >= 0; i--) {
            j = 0;
            cells      = rows[i+1].cells;
            ranks[i]   = parseInt(cells[j++].innerHTML.replace(/\./g,""));
            players[i] = cells[j++];

            while(players[i].firstChild) {
                players[i] = players[i].firstChild;
            }

            players[i] = players[i].nodeValue;
            try {
                //TODO: Saubere Loesung
                pIds[i] = cells[j++].innerHTML.match(pIdRegExp)[1];
            } catch(e) { }
            alliances[i] = cells[j++];
            while(alliances[i].lastChild) {
            	alliances[i] = alliances[i].lastChild;
            }
            alliances[i] = GTPlugin_TrimString(alliances[i].nodeValue);
            points[i]    = parseInt(cells[j].innerHTML.replace(/\./g,""));
        }

        var data = "";
        data += "&ranks=" + ranks.join("|");
        data += "&players=" + players.join("|");
        data += "&pIds=" + pIds.join("|");
        data += "&alliances=" + alliances.join("|");
        data += "&points=" + points.join("|");
    } else { //Alliances
        var ranks = new Array(100);
        var alliances = new Array(100);
        var members = new Array(100);
        var points = new Array(100);
        var j;
        for(var i = rows.length - 2; i >= 0; i--) {
            j = 0;
            cells = rows[i+1].cells;
            ranks[i] = parseInt(cells[j++].innerHTML.replace(/\./g,""));
            alliances[i] = cells[j++];
            while(alliances[i].firstChild)
            alliances[i] = alliances[i].firstChild;
            alliances[i] = alliances[i].nodeValue;
            j++;
            members[i] = cells[j++].innerHTML.replace(/\./g,"");
            points[i] = cells[j++].innerHTML.replace(/\./g,"");
        }
        var data = "";
        data += "&ranks=" + ranks.join("|");
        data += "&alliances=" + alliances.join("|");
        data += "&members=" + members.join("|");
        data += "&points=" + points.join("|");
    }
    return data;
}

function GTPlugin_get_galaxyview_data(docroot) {
	// reutrn string as format: solar_system\n{ind|planetname|moonsize|metal_debris|crystal_debris|playername|playerrank|playerstatus|alliance|allyrank|allymember|playerid\n}+
    var tables = docroot.getElementsByTagName('table');
    var tabind;
    //maximum 21 rows: one row for "Solar System x:xxx, one row for table title; 15 rows for planets, one row for outer space (16), one row for missiles, one row for fleetstatus
    var maxrows = 21;
    for(tabind=0; tabind<tables.length; tabind++)
    	if(tables[tabind].rows.length>=15 && tables[tabind].rows.length<=maxrows) break;

    var rows = tables[tabind].rows;
    var cells;
    var galaxyview = new Array(15);
    var galaxy_content;
    var posRegExp = />(\d+)<\/a>/;
    var debrisRegExp;
    var playerRankRegExp;
    var allyRankRegExp;
    var moonRegExp;

    var moonsize;
    var metal_debris;
    var crystal_debris;
    var planetname;
    var corrector = 0;
    // break if foxgame reduced galaxyview or enhanced debris field is enabled
    var foxgame = GTPlugin_IsFGRemovePlanets();
    var foxgameaddmilosbuttons = GTPlugin_IsFGAddMilosButtons();
    if (foxgame == true) {
        corrector = 1; // foxgame removes the planet, so substract 1 from cellarray
    }
    var btncorrector = 0;
    if (foxgameaddmilosbuttons) {
    	btncorrector = 1;
    }
    
    // find the word for "solar system" to determine the language later
    cells = rows[0+btncorrector].cells;
    var solar_system = cells[0].innerHTML;
    solar_system = solar_system.replace(/^\s*/,"").replace(/\s*$/,"");
    var ss = solar_system.split(" ",1); // "System" in english
    if(ss == "System") { // english
        debrisRegExp = />Metal:<\/th><th>([\d\.]+)<\/th><\/tr><tr><th>Crystal:<\/th><th>([\d\.]+)</;
    	playerRankRegExp = /[;>](.+)\s+ranked\s+(\d+)[&<]/;
    	allyRankRegExp = /[;>]Alliance\s+(.+)\s+ranked\s+(\d+)\s+consisting of\s+(\d+)\s+member\(s\)[&<]/;
    	moonRegExp = />size:\s*<\/td><th>([\d\.]+)</;
    } else if(ss == "太阳系") {
        debrisRegExp = />金属：<\/th><th>([\d\.]+)<\/th><\/tr><tr><th>晶体：<\/th><th>([\d\.]+)</;
    	playerRankRegExp = /[;>]玩家\s+(.+)\s+排名\s+(\d+)[&<]/;
    	allyRankRegExp = /[;>]联盟\s+(.+)\s+排名\s+(\d+)\s+有\s+(\d+)\s+名会员[&<]/;
    	moonRegExp = />大小：<\/td><th>([\d\.]+)</;
    } else if( ss == "太陽系") {
        debrisRegExp = />金屬:<\/th><th>([\d\.]+)<\/th><\/tr><tr><th>晶體:<\/th><th>([\d\.]+)</;
    	playerRankRegExp = /[;>]玩家\s+(.+)\s+排名\s+(\d+)[&<]/;
    	allyRankRegExp = /[;>]聯盟\s+(.+)\s+排名\s+(\d+)\s+有\s+(\d+)\s+名會員[&<]/;
    	moonRegExp = />大小：<\/td><th>([\d\.]+)</;
    }
    
    //solar_system = solar_system.replace(/\s/,"");

    for(var i = 2+btncorrector; i < 17+btncorrector; i++) {
        // reset data
        moonsize = 0;
        metal_debris = 0;
        crystal_debris = 0;
        playerid = 0;
        playerstatus = "";
        playername = "";
        playerrank = -1;
        planetname = "";
        alliance = "";
        allyrank = -1;
        allymember = 0;

        cells = rows[i].cells;
        
	if(cells[3-corrector].getElementsByTagName('img').length >0) {
		//moon exists
		try {
    			moonsize = parseInt(cells[3-corrector].getElementsByTagName('img')[0].getAttribute('alt').match(/([\d\.]+)/)[1].replace(/\./g,""));
    		} catch(e) {
    			try {
    				//v0.78
    				moonsize = parseInt(cells[3-corrector].getElementsByTagName('a')[0].getAttribute('onmouseover').match(moonRegExp)[1].replace(/\./g,""));
    			} catch(e) { 
    				//has moon, but parse failed
    				moonsize = 1;
    			}
    		}	
    	}
        try {
            var tmp = cells[4-corrector].getElementsByTagName('a')[0].getAttribute('onmouseover').match(debrisRegExp);
            metal_debris = parseInt(tmp[1].replace(/\./g,""));
            crystal_debris = parseInt(tmp[2].replace(/\./g,""));
        } catch(e) { /* no debris field */ }

        if (foxgame == true) {
            try {
                // in reach of a phalanx
                planetname = cells[2-corrector].getElementsByTagName('a')[0].getElementsByTagName('a')[0].innerHTML;
            }catch(e) { /* no planet */
                // not in reach of a phalanxy
                try {
                    planetname = cells[2-corrector].getElementsByTagName('a')[0].innerHTML;
                }catch(e) { /* no planet */ }
            }

        } else {
            try {
                // planet is in reach of a phalanx
                planetname = cells[2].getElementsByTagName('a')[0].innerHTML;
            } catch(e) {
                // not in reach of a phalanx
                planetname = cells[2].innerHTML;
            }
        }

        planetname = planetname.replace(/\([0-9a-zA-Z\*\s]+\)/,""); // remove activity behind planet name
        planetname = planetname.replace("&nbsp;","");
        planetname = planetname.replace(/\s/,"");

        galaxy_content = parseInt(cells[0].innerHTML.match(posRegExp)[1])+"|"; // position
        galaxy_content += planetname+"|"; // planetname
        galaxy_content += moonsize+"|"; // moon
        galaxy_content += metal_debris+"|"; // metal debris field
        galaxy_content += crystal_debris+"|"; // crystal debris field
        try {
            playername = cells[5-corrector].getElementsByTagName('span')[0].innerHTML; // playername
            // get player rank
            var tmp = cells[5-corrector].getElementsByTagName('a')[0].getAttribute('onmouseover').match(playerRankRegExp);
            if(tmp && tmp.length>1) {
            	playerrank = parseInt(tmp[2]);
            }
            // get playerstats - at max 6 (i,I,u,g,s,n)
            for (var j=1; j<7; j++) {
                playerstatus += cells[5-corrector].getElementsByTagName('span')[j].innerHTML;
            }
        } catch(e) { /* catch when there is no player or last playerstatus was found */ }
        galaxy_content += playername+"|";
        galaxy_content += playerrank+"|";  // add playerrank
        galaxy_content += playerstatus+"|"; // add playerstats
        try {
            try {
                // own alliance
                alliance = cells[6-corrector].getElementsByTagName('a')[0].getElementsByTagName('span')[0].innerHTML; // alliance
            } catch(e) {
                // another alliance
                alliance = cells[6-corrector].getElementsByTagName('a')[0].innerHTML; // alliance
            }
            alliance = alliance.replace(/\n+/,"");
	        var tmp = cells[6-corrector].getElementsByTagName('a')[0].getAttribute('onmouseover').match(allyRankRegExp);
	        if(tmp && tmp.length>3) {
	        	allyrank = parseInt(tmp[2]);
	        	allymember = parseInt(tmp[3]);
	        }
        } catch(e) { /* catch when there is no alliance */ }
        galaxy_content += alliance+"|";
        galaxy_content += allyrank+"|";
        galaxy_content += allymember+"|";

        // try to find the playerid
        try {
            playerid = parseInt(cells[7-corrector].getElementsByTagName('a')[1].getAttribute('href').match(/messageziel=(\d+)/)[1]);
        } catch(e) { /* no playerid found (no planet or the players' planet */ }
        galaxy_content += playerid;

        // delete all \n within this string
        galaxy_content = galaxy_content.replace(/\n+/,"");
        galaxyview[i-2] = galaxy_content;
    }
    var galaxystring = solar_system + "\n" + galaxyview.join("\n");
    return galaxystring;
}


function GTPlugin_sendText(typ,text,source_url) {
    try {
        if (prefs.getCharPref("gtplugin.settings.ogameurl1").length>0 && source_url.toLowerCase().search(prefs.getCharPref("gtplugin.settings.ogameurl1").toLowerCase()) > -1) {
            var txt = "user="+prefs.getCharPref("gtplugin.settings.username1")+"&password="+prefs.getCharPref("gtplugin.settings.password1")+"&typ="+typ;
            var url = prefs.getCharPref("gtplugin.settings.url");
        } else if (prefs.getCharPref("gtplugin.settings.ogameurl2").length>0 && source_url.toLowerCase().search(prefs.getCharPref("gtplugin.settings.ogameurl2").toLowerCase()) > -1) {
            var txt = "user="+prefs.getCharPref("gtplugin.settings.username2")+"&password="+prefs.getCharPref("gtplugin.settings.password2")+"&typ="+typ;
            var url = prefs.getCharPref("gtplugin.settings.url");
        } else if (prefs.getCharPref("gtplugin.settings.ogameurl3").length>0 && source_url.toLowerCase().search(prefs.getCharPref("gtplugin.settings.ogameurl3").toLowerCase()) > -1) {
            var txt = "user="+prefs.getCharPref("gtplugin.settings.username3")+"&password="+prefs.getCharPref("gtplugin.settings.password3")+"&typ="+typ;
            var url = prefs.getCharPref("gtplugin.settings.url");
        } else if (prefs.getCharPref("gtplugin.settings.ogameurl4").length>0 && source_url.toLowerCase().search(prefs.getCharPref("gtplugin.settings.ogameurl4").toLowerCase()) > -1) {
            var txt = "user="+prefs.getCharPref("gtplugin.settings.username4")+"&password="+prefs.getCharPref("gtplugin.settings.password4")+"&typ="+typ;
            var url = prefs.getCharPref("gtplugin.settings.url");
        } else if (prefs.getCharPref("gtplugin.settings.ogameurl5").length>0 && source_url.toLowerCase().search(prefs.getCharPref("gtplugin.settings.ogameurl5").toLowerCase()) > -1) {
            var txt = "user="+prefs.getCharPref("gtplugin.settings.username5")+"&password="+prefs.getCharPref("gtplugin.settings.password5")+"&typ="+typ;
            var url = prefs.getCharPref("gtplugin.settings.url");
        } else {
            document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.unknownuni");
            return 0;
        }

        var responsetext = "";

        if (typ == "stats") {
            txt = txt + "&who="+GTPlugin_selectedWer+"&what="+GTPlugin_selectedTyp;
            if (GTPlugin_selectedWer == 0) responsetext = GTPlugin_GetLocString("statsupdated.playerprefix");
            if (GTPlugin_selectedWer == 1) responsetext = GTPlugin_GetLocString("statsupdated.allyprefix");
            if (GTPlugin_selectedTyp == 0) responsetext = responsetext + GTPlugin_GetLocString("statsupdated.scoreinfix")+GTPlugin_selectedRanks+GTPlugin_GetLocString("statsupdated.suffix");
            if (GTPlugin_selectedTyp == 1) responsetext = responsetext + GTPlugin_GetLocString("statsupdated.fleetinfix")+GTPlugin_selectedRanks+GTPlugin_GetLocString("statsupdated.suffix");
            if (GTPlugin_selectedTyp == 2) responsetext = responsetext + GTPlugin_GetLocString("statsupdated.researchinfix")+GTPlugin_selectedRanks+GTPlugin_GetLocString("statsupdated.suffix");
        }

        if (typ == "galaxy") {
            txt = txt + "&galaxy="+GTPlugin_selectedGalaxy+"&system="+GTPlugin_selectedSystem;
            responsetext = GTPlugin_GetLocString("galaxyupdated.prefix")+GTPlugin_selectedGalaxy+":"+GTPlugin_selectedSystem+GTPlugin_GetLocString("galaxyupdated.suffix");
        }

        if (typ == "reports") {
            responsetext = GTPlugin_GetLocString("reportsupdated");
        }
        if (typ == "allyhistory") {
            responsetext = GTPlugin_GetLocString("allyhistoryupdated");
        }

        txt = txt + "&content=" + encodeURIComponent(text); // needed to send data with special chars like \s or \n


        var httpRequest = new XMLHttpRequest();
        httpRequest.open("POST", url, true); // 3. Parameter ist für asynchronen Transfer n?tig
        httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        httpRequest.setRequestHeader("Content-Length", txt.length);
	
        httpRequest.onreadystatechange = function () {
        	try{
            if (httpRequest.readyState != 4) {
                //alert('Bad Ready State: ' + httpRequest.status);
                //document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.badreadystate")+httpRequest.status;
                return 0;
            } else {
                /*
                * Status Codes:
                - 200 = gernally okay
                - 403 = forbidden
                - Response Text:
                - 601: galaxy view inserted
                - 602: problem with inserting galaxy view
                - 611: report inserted
                - 612: at least one report was wrong
                - 621: stats updated
                - 622: stats not updated
                - 623: stats not changed
                - 631: allyhistory updated
                - 632: allyhistory not updated
                - 642: unmatched ogame server
                - 682: not supported in current version
                */

                if (httpRequest.status == 403) { // forbidden
                    document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.permissiondenied");
                    return 0;
                } else if (httpRequest.status == 404) { // Server responsed
                    document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.pagenotfound");
                    return 0;
                } else if (httpRequest.status == 200) { // Server responsed
                    if ((parseInt(httpRequest.responseText) == 601) || (parseInt(httpRequest.responseText) == 611) ||
                    (parseInt(httpRequest.responseText) == 621) || (parseInt(httpRequest.responseText) == 631)) { // gv updated
                        document.getElementById("GTPlugin-status-view").value = responsetext;
			GTPlugin_Doc = null;
			document.getElementById("GTPlugin-uploads").disabled = true;                        
                        return 1;
                    } else if (parseInt(httpRequest.responseText) == 602) { // gv not updated
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.gvnotupdated");
                        return 0;
                    } else if (parseInt(httpRequest.responseText) == 612) { // at least 1 report not inserted
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.reporterror");
                        return 0;
                    } else if (parseInt(httpRequest.responseText) == 622) { // stats not updated
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.statserror");
                        return 0;
                    } else if (parseInt(httpRequest.responseText) == 623) { // stats not changed
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.statssame");
                        return 0;
                    } else if (parseInt(httpRequest.responseText) == 632) { // allyhistory not updated
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.allyhistoryerror");
                        return 0;
                    } else if (parseInt(httpRequest.responseText) == 642) { // unmatched ogame server
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.unmatchedoserror");
                        return 0;
                    } else if (parseInt(httpRequest.responseText) == 682) { // not supported
                        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.notsupported");
                        return 0;
                    }
                } else {
                    document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.badstatuscode")+httpRequest.status;
                    return 0;
                }
            }
        	}catch (e) {
        		document.getElementById("GTPlugin-status-view").value = "unknown exception: " + e;
        	}
        };
        httpRequest.send(txt);
        return 0;        
    } catch (e){
        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("error.gtservernotfound");
        //alert('An error has occured calling the external site: '+e);
        return 0;
    }
    return 0;
}

function GTPlugin_Uploads() {
	GTPlugin_result = 0;
	if(!GTPlugin_Doc || !GTPlugin_Doc.location || !GTPlugin_Doc.location.href) {
		document.getElementById("GTPlugin-uploads").disabled = true;
		return GTPlugin_result;
	}
	var text;
	var doc = GTPlugin_Doc;
        if(GTPlugin_IsGalaxy(doc)) {                	
            text = GTPlugin_get_galaxyview_data(doc);
            GTPlugin_result = GTPlugin_sendText("galaxy",text,doc.location.href);
        } else if(GTPlugin_IsStat(doc)) {
            text = GTPlugin_getStatsText(doc);
            GTPlugin_result = GTPlugin_sendText("stats",text,doc.location.href);
        }
        /*        
	else if(doc.location.href.search(/\/game\/messages\.php/i) > -1) {
            document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("reportsfound");
            GTPlugin_Doc = doc;
        } else if((doc.location.href.search(/\/game\/allianzen\.php/i) > -1) && (doc.location.href.search("&a=4") > -1)) {
		// Allyhistory
            GTPlugin_result = GTPlugin_sendText("allyhistory",doc.getElementsByTagName("table")[4].innerHTML,doc.location.href);
        }
	*/
	if(GTPlugin_result == 1){
		GTPlugin_Doc = null;
		document.getElementById("GTPlugin-uploads").disabled = true;
	}
	return GTPlugin_result;
}

function GTPlugin_getPrefs() {
    var ipf = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    // preferences initialization
    if(!ipf.prefHasUserValue("gtplugin.settings.ogameurl1"))  	ipf.setCharPref("gtplugin.settings.ogameurl1", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.ogameurl2"))   	ipf.setCharPref("gtplugin.settings.ogameurl2", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.ogameurl3"))   	ipf.setCharPref("gtplugin.settings.ogameurl3", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.ogameurl4"))   	ipf.setCharPref("gtplugin.settings.ogameurl4", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.ogameurl5"))   	ipf.setCharPref("gtplugin.settings.ogameurl5", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.ogameurl1"))  	ipf.setCharPref("gtplugin.settings.ogameurl1", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.username2"))   	ipf.setCharPref("gtplugin.settings.username2", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.username3"))   	ipf.setCharPref("gtplugin.settings.username3", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.username4"))   	ipf.setCharPref("gtplugin.settings.username4", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.username5"))   	ipf.setCharPref("gtplugin.settings.username5", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.password1"))   	ipf.setCharPref("gtplugin.settings.password1", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.password2"))   	ipf.setCharPref("gtplugin.settings.password2", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.password3"))   	ipf.setCharPref("gtplugin.settings.password3", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.password4"))   	ipf.setCharPref("gtplugin.settings.password4", "");
    if(!ipf.prefHasUserValue("gtplugin.settings.password5"))   	ipf.setCharPref("gtplugin.settings.password5", "");
    	
    if(!ipf.prefHasUserValue("gtplugin.settings.url"))   	ipf.setCharPref("gtplugin.settings.url", "http://www.utblog.com/galaxytool/secret/galaxyplugin.php");
    if(!ipf.prefHasUserValue("gtplugin.settings.alarmsoundurl"))   	ipf.setCharPref("gtplugin.settings.alarmsoundurl", "http://www.utblog.com/galaxytool/alarm.mid");
    
    if(!ipf.prefHasUserValue("gtplugin.settings.autostarten"))   	ipf.setBoolPref("gtplugin.settings.autostarten", false);
    if(!ipf.prefHasUserValue("gtplugin.settings.autouploads"))   	ipf.setBoolPref("gtplugin.settings.autouploads", true);

    return ipf;
}

function GTPlugin_Activate() {
    if (GTPlugin_activated == 0) {
        GTPlugin_activated = 1;
        document.getElementById("GTPlugin-activate").setAttribute("tooltiptext", GTPlugin_GetLocString("toolbar.deactivate.t"), 0);
        document.getElementById("GTPlugin-activate").setAttribute("label", GTPlugin_GetLocString("toolbar.deactivate"), 0);
        document.getElementById("GTPlugin-activate").setAttribute("image", "chrome://galaxyplugin/skin/images/disable.gif", 0);
        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("toolbar.deactivate.status");
        //        window.addEventListener("load", init, true);
    } else {
        GTPlugin_activated = 0;
        document.getElementById("GTPlugin-activate").setAttribute("tooltiptext", GTPlugin_GetLocString("toolbar.activate.t"), 0);
        document.getElementById("GTPlugin-activate").setAttribute("label", GTPlugin_GetLocString("toolbar.activate"), 0);
        document.getElementById("GTPlugin-activate").setAttribute("image", "chrome://galaxyplugin/skin/images/enable.gif", 0);
        document.getElementById("GTPlugin-status-view").value = GTPlugin_GetLocString("toolbar.activate.status");
        GTPlugin_EnableAlarm();
        GTPlugin_EnableGRefresh();
        //        window.removeEventListener("load", init, true);
    }
}

function GTPlugin_EnableAlarm() {
    if (GTPlugin_activated == 1 && GTPlugin_alarmenabled == 0) {
	GTPlugin_alarmenabled = 1;
        document.getElementById("GTPlugin-alarm").setAttribute("tooltiptext", GTPlugin_GetLocString("toolbar.dalarm.t"), 0);
        document.getElementById("GTPlugin-alarm").setAttribute("label", GTPlugin_GetLocString("toolbar.dalarm"), 0);
        document.getElementById("GTPlugin-alarm").setAttribute("image", "chrome://galaxyplugin/skin/images/dalarm.gif", 0);
        document.getElementById("GTPlugin-alarm-view").value = GTPlugin_GetLocString("toolbar.alarminfo.standby");
    } else {
        GTPlugin_alarmenabled = 0;
        document.getElementById("GTPlugin-alarm").setAttribute("tooltiptext", GTPlugin_GetLocString("toolbar.alarm.t"), 0);
        document.getElementById("GTPlugin-alarm").setAttribute("label", GTPlugin_GetLocString("toolbar.alarm"), 0);
        document.getElementById("GTPlugin-alarm").setAttribute("image", "chrome://galaxyplugin/skin/images/alarm.gif", 0);
        document.getElementById("GTPlugin-alarm-view").value = GTPlugin_GetLocString("toolbar.alarminfo.disabled");
    }
}

function GTPlugin_EnableGRefresh() {
    if (GTPlugin_activated == 1 && GTPlugin_grefreshenabled == 0) {
	GTPlugin_grefreshenabled = 1;
        document.getElementById("GTPlugin-grefresh").setAttribute("tooltiptext", GTPlugin_GetLocString("toolbar.dgrefresh.t"), 0);
        document.getElementById("GTPlugin-grefresh").setAttribute("label", GTPlugin_GetLocString("toolbar.dgrefresh"), 0);
        document.getElementById("GTPlugin-grefresh").setAttribute("image", "chrome://galaxyplugin/skin/images/drefresh.gif", 0);
    } else {
        GTPlugin_grefreshenabled = 0;
        document.getElementById("GTPlugin-grefresh").setAttribute("tooltiptext", GTPlugin_GetLocString("toolbar.grefresh.t"), 0);
        document.getElementById("GTPlugin-grefresh").setAttribute("label", GTPlugin_GetLocString("toolbar.grefresh"), 0);
        document.getElementById("GTPlugin-grefresh").setAttribute("image", "chrome://galaxyplugin/skin/images/refresh.gif", 0);
    }
}

function GTPlugin_Options() {
    var windowobject = window.openDialog("chrome://galaxyplugin/content/galaxyoptions.xul", "options", "chrome,width=600,height=300");
}

function GTPlugin_TrimString(string) {
    // Return empty if nothing was passed in
    if (!string) return "";

    // Efficiently replace any leading or trailing whitespace
    var value = string.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');

    // Replace any multiple whitespace characters with a single space
    value = value.replace(/\s+/g, ' ');

    // Return the altered string
    return value;
}

function GTPlugin_GetLocString(string)
{
    var locString = document.getElementById( "gtStrings" ).getString( "gt_" + string );

    locString = locString.replace(/^[.]/, '');
    locString = locString.replace(/[.]$/, '');
    return locString;
}

function GTPlugin_IsFGRemovePlanets()
{
    var foxgame = false;
    try {
        if (fgGetBooleanPref("foxgameRemovePlanets",true)) {
            // reduced galaxyview activated
            foxgame = true;
        } else {
            // foxgame installed, but no reduced galaxyview activated
	 	foxgame = false;
        }
    } catch(e) {
        // no foxgame installed
	foxgame = false;
    }
    return foxgame;
}

function GTPlugin_IsFGAddMilosButtons()
{
    var foxgame = false;
    try {
        if (fgGetBooleanPref("foxgameAddMilosButtons",true)) {
            // reduced galaxyview activated
            foxgame = true;
        } else {
            // foxgame installed, but no reduced galaxyview activated
	 	foxgame = false;
        }
    } catch(e) {
        // no foxgame installed
	foxgame = false;
    }
    return foxgame;
}
